import {Component, OnInit} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {UtilityService} from '../../../../service/utils.service';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {ActivatedRoute, Router} from '@angular/router';
import {MenuItem, TreeNode} from 'primeng/api';
import {appConfig} from '../../../../service/common';
import * as _ from 'lodash';

@Component({
    selector: 'app-role-func',
    templateUrl: './role-func.component.html',
})
export class RoleFuncComponent implements OnInit {
    operatorGuid: string;
    treedata: any[]; // tree组件数据
    searchTitle: string; // 树搜索框文字
    treemenus: MenuItem[];
    jurisdictionTree:any[] // 树节点保存
    checked = false; // 全选按钮是否显示
    selectionType = 'single'
    isData = true
    noMenu  = true; // 没有右击
    funcInfo: any; // 功能信息
    operator: any; // 操作员信息
    operatorName: ''; // 操作员名称
    isDisabledButton = true; // 默认都是禁选的
    isSaveEdit = true; // 修改和保存二选一按钮, 默认是修改按钮
    roleTxt: any[]; // 角色信息
    radioValue: any; // 角色功能组radio筛选
    constructor(
        private http: _HttpClient,
        private router: Router,
        private activatedRoute: ActivatedRoute, // 注入路由，接收到参数
        private nznot: NzNotificationService,
        private utilityService: UtilityService,
    ) { }
    checkOptionsOne: any; // 验证行为权限的数组
    copycheckOptionsOne: any; // 拷贝数组
    nocheckOptionsOne: any; // 不验证行为权限的数组

    ngOnInit() {
        this.operatorGuid = this.activatedRoute.snapshot.params.id; // 拿到父组件传过来的组织机构的guid来进行操作
        this.searchTitle = '请输入功能名称/功能代码'
        this.initData()
        this.getOperatorInfo(this.operatorGuid);
    }

    // 根据id查询操作员详情
    getOperatorInfo(id) {
        this.utilityService.getData(appConfig.serverUrl + appConfig.API.acOperatorsAdd + '/' + id)
            .subscribe(
                (val) => {
                    this.operator = val.result;
                    this.operatorName = val.result.operatorName;
                }
            );
    }

    initData() {
        this.treedata = [ // 默认根节点
            {
                'label': '应用列表',
                'data': 'default Role',
                'guid': 'appRoot',
                'expandedIcon': '',
                'collapsedIcon': '',
                'children': [{}]
            }
        ];
        let objJson = {
            // appId: 'null',
            operatorId: this.operatorGuid
        }
        this.utilityService.postData(appConfig.serverUrl +  appConfig.API.queryFuncBehaveFilterByOperatorApp, objJson)
            .subscribe(
                (val) => {
                    console.log(val.result.allData)
                    for(var i = 0; i < val.result.allData.length; i ++) {
                        val.result.allData[i].label = val.result.allData[i].appName;
                        val.result.allData[i].collapsedIcon  = 'anticon anticon-home';
                        val.result.allData[i].expandedIcon  = 'anticon anticon-home';
                        if(val.result.allData[i].funcList.length > 0) { // 代表有功能和行为
                            val.result.allData[i].children  = val.result.allData[i].funcList;
                            for(let s = 0; s < val.result.allData[i].children.length; s ++ ) {
                                val.result.allData[i].children[s].label = val.result.allData[i].children[s].funcName;
                                if (val.result.allData[i].children[s].exit === 'true') { // true代表一个行为没有选择，没有配置过行为
                                } else { // 代表已经有了，那么对勾进行展示
                                    console.log(val.result.allData[i].children[s])
                                    val.result.allData[i].children[s].collapsedIcon = 'fa fa-check';
                                }
                            }
                        }
                    }
                    this.treedata[0].children = val.result.allData; // 绑定树节点
                });

        this.treedata.forEach( node => {
            this.expandRecursive(node, true);
        });
    }

    // 展开所有树节点的方法
    private expandRecursive(node:TreeNode, isExpand:boolean){
        this.roleTxt = [];
        node.expanded = isExpand;
        if(node.children){
            node.children.forEach( childNode => {
                this.expandRecursive(childNode, isExpand);
            } );
        }
    }

  /*  getQuery(event) {
        if(event.guid !== 'appRoot') { // 请求跟目录
            let objJson = {
                appId: event.guid,
                operatorId: this.operatorGuid
            }
            this.utilityService.postData(appConfig.serverUrl +  appConfig.API.queryFuncBehaveFilterByOperatorApp, objJson)
                .subscribe(
                    (val) => {
                        for(var i = 0; i < val.result.length; i ++) {
                            val.result[i].label = val.result[i].funcName;
                            if (val.result[i].exit === 'true') { // true代表一个行为没有选择，没有配置过行为
                            } else { // 代表已经有了，那么对勾进行展示
                                val.result[i].collapsedIcon = 'fa fa-check';
                            }
                        }
                        event.children = val.result; // 绑定树节点
                    });
        }
    }*/

    // 下拉的时候树结构调用
    Unfold(event) {
        this.roleTxt = [];
        // this.getQuery(event.node)
    }


    id:any;
    tabShow = false
    // 选中节点操作

    // 判断是否全部选中，如果全部选中，那么全选按钮选中，反之 不选中
    checkAdult(age) {
        return age.exit === 'false'; // 判断是否全部是false
    }


    TreeSelect(event) {
        this.roleTxt = [];
        this.radioValue = 'all'; // 默认所有
        if (event.node.childs) { // 如果存在，代表功能
            this.tabShow = true;
            this.funcInfo = event.node;
            if(event.node.childs.every(this.checkAdult)) { // 利用every属性，判断是否全部选中，如果全部选中，全选按钮为true
                this.checked = true;
            } else {
                this.checked = false;
            }
            let noArray = []; // 不验证行为数组
            let Array = []; // 验证行为数组

            for(var i = 0 ; i < event.node.childs.length; i ++) {
                event.node.childs[i].label = event.node.childs[i].funcName
                event.node.childs[i].guid = event.node.childs[i].guid;
                if(event.node.childs[i].exit === 'true') { // 如果是true字符串，代表是不能勾选，false，代表勾选
                    event.node.childs[i].checked = false;
                    event.node.childs[i].ifcheck = false; // 本身就不勾选
                } else if(event.node.childs[i].exit === 'false' &&  event.node.childs[i].authType !== 'forbid') { // 选中只有是false。并且不是特别禁止的才可以
                    event.node.childs[i].checked = true;
                    event.node.childs[i].ifcheck = true; // 本身就勾选
                }
            }
            Array = _.clone(event.node.childs); // 深拷贝一份
            this.nocheckOptionsOne = _.remove(Array, function(n) { // 不需要验证权限的
                return n.ischeck === '否';
            });
            for(let  s = 0 ; s <　this.nocheckOptionsOne.length; s ++ ) {
                this.nocheckOptionsOne[s].checked = true; // 默认选中
            }
            this.copycheckOptionsOne = _.clone(Array);
            this.checkOptionsOne = Array; // 需要验证权限的
        } else {
            this.tabShow = false;
        }
        this.reset(event.node.childs);
    }


    // 查询功能下的行为方法
    queryFunBeh(event) {
        this.roleTxt = [];
        let objJson = {
            appId: event.node.parent.guid,
            operatorId:this.operatorGuid,
            funcId: event.node.guid
        }
        this.utilityService.postData(appConfig.serverUrl +  appConfig.API.queryBehaveByOperator, objJson)
            .subscribe(
                (val) => {
                });

        this.reset(this.checkOptionsOne);
    }


    changeCheckbox(event) {
            this.roleTxt = [];
            if(this.checkOptionsOne.every(item => item.checked ===  true)) { // 利用every属性，判断是否全部选中，如果全部选中，全选按钮为true
                this.checked = true;
            } else {
                this.checked = false;
            }
            event.forEach(item => {
                item.exit = !item.checked + '';
            })
        this.reset(this.checkOptionsOne);
    }



    // 树节点搜索框的内容
    searchVal($event) {
        console.log($event);
        if($event === '') {
            this.initData();
            this.tabShow = false;
        } else {
            let jsonObj = {
                guid: 'null',
                name: $event,
                operatorId: this.operatorGuid
            }
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.queryFuncBehaveFilterByOperatorApp, jsonObj)
                .subscribe(
                    (val) => {
                        this.tabShow = false;
                        if (val.code === '200' || val.code === 200) {
                            console.log(val.result)
                            this.treedata = [ // 默认根节点
                                {
                                    'label': '应用列表',
                                    'data': 'default Role',
                                    'guid': 'appRoot',
                                    'expandedIcon': '',
                                    'collapsedIcon': '',
                                    'children': [{}]
                                }
                            ];
                            this.treedata[0].children = val.result.allData;
                            for(let i = 0; i < val.result.allData.length; i ++) {
                                console.log(val.result.allData[i]);
                                val.result.allData[i].label = val.result.allData[i].appName;
                                if(val.result.allData[i].funcList.length > 0) { // 说明有功能
                                    for(let s = 0; s < val.result.allData[i].funcList.length; s++) {
                                        val.result.allData[i].funcList[s].label = val.result.allData[i].funcList[s].funcName;
                                    }
                                    val.result.allData[i].children = val.result.allData[i].funcList;
                                }
                            }
                            // 展开所有的
                            this.treedata.forEach( node => {
                                this.expandRecursive(node, true);
                            } );
                        }
                    },
                );
        }
    }





    // 修改按钮展现
    edit() {
        this.isSaveEdit = false; // 保存按钮显示,修改按钮隐藏
        this.isDisabledButton = false; // 改成可以修改
    }


    save() {
        this.isSaveEdit = true; // 修改按钮显示,保存按钮隐藏
        this.isDisabledButton = true; // 改成不可以修改
       /* let array = [];
        let treeArray = this.treedata[0].children;
        for(let i = 0; i < treeArray.length; i++) { // 所有应用
            for(let j = 0; j < treeArray[i].children.length; j++) { // 所有功能
                if(treeArray[i].children[j].funcCode) {
                    for(let s = 0 ; s < treeArray[i].children[j].childs.length; s ++) {
                        if(treeArray[i].children[j].childs[s].childs === '') {
                            if(treeArray[i].children[j].childs[s].checked  ||  treeArray[i].children[j].childs[s].exit === 'false') {
                                array.push(treeArray[i].children[j].childs[s].guid)
                            }
                        }
                    }
                }
            }
        }


        let objJson = {
            behaveIdList:array,
            operatorId:this.operatorGuid
        }*/
        let objJson = {
                dataList : this.selectArray,
                operatorGuid: this.operatorGuid
            }
        console.log(objJson)
        this.utilityService.postData(appConfig.serverUrl +  appConfig.API.rolebatchAdd, objJson)
            .subscribe(
                (val) => {
                    console.log(val.result)
                    this.nznot.create('success', val.msg , val.msg);
                },
                (error) => {
                    this.nznot.create('error', error.msg , error.msg);
                });
    }


    clickFunc($event) {
        if($event === 'reset') {
            this.initData();
            this.tabShow = false;
        } else if($event === 'expand') { // 全部展开方法
            // 展开所有的
            this.treedata.forEach( node => {
                this.expandRecursive(node, true);
            } );
        } else {
            this.tabShow  = false;
            this.treedata.forEach( node => {
                this.expandRecursive(node, false);
            } );
        }
    }
    // 重置
    reset(checkOptionsOne){
        this.roleTxt = [];
        for(var i = 0 ; i < checkOptionsOne.length; i ++) {
            if (checkOptionsOne[i].checked === true) { // 如果是true字符串，代表是没有勾选
                this.roleTxt.push(checkOptionsOne[i].funcDesc);
            }
        }
    }


    // radio选择框
    selectRaido(item) {
        this.checkOptionsOne = this.copycheckOptionsOne; // 默认等于所有的
         if(item === 'all') {

         } else if (item === 'fromRole') {
             let array = [];
             for(let s = 0; s < this.copycheckOptionsOne.length; s ++ ){
                    if(this.copycheckOptionsOne[s].fromRole === 'Y') {
                        array.push(this.copycheckOptionsOne[s])
                    }
             }
             this.checkOptionsOne = array;
         } else if (item === 'allow') { // 特别允许
             let array = [];
             for(let s = 0; s < this.copycheckOptionsOne.length; s ++ ){
                 if(this.copycheckOptionsOne[s].fromRole === 'N' && this.copycheckOptionsOne[s].authType === 'remit') {
                     array.push(this.copycheckOptionsOne[s])
                 }
             }
             this.checkOptionsOne = array;
         } else if (item === 'prohibition') { // 特别禁止
             let array = [];
             for(let s = 0; s < this.copycheckOptionsOne.length; s ++ ) {
                 if(this.copycheckOptionsOne[s].fromRole === 'N' && this.copycheckOptionsOne[s].authType === 'forbid') {
                     array.push(this.copycheckOptionsOne[s])
                 }
             }
             this.checkOptionsOne = array;
         } else if (item === 'Unallocated') { // 为分配
             let array = [];
             for(let s = 0; s < this.copycheckOptionsOne.length; s ++ ) {
                 if(this.copycheckOptionsOne[s].fromRole === 'N' && this.copycheckOptionsOne[s].checked === false) {
                     array.push(this.copycheckOptionsOne[s])
                 }
             }
             this.checkOptionsOne = array;
         }
    }

    // 筛选select
    selectFilder = [
        {key: 'all', value : '查看所有'},
        {key: 'fromRole', value : '来自角色'},
        {key: 'prohibition', value : '特别禁止'},
        {key: 'allow', value : '特别允许'},
        {key: 'Unallocated', value : '未分配'},
    ]

    // 全选按钮
    allSelect($event){
        let copyAppry = _.clone(this.checkOptionsOne)
        if($event) { // 代表全选, 那么exit的状态是false
            /* 双层循环，删除this.selectArray 重复的*/
            for(let i = 0 ; i < copyAppry.length; i ++) {
                for(let s = 0; s < this.selectArray.length; s ++ ) {
                    if(copyAppry[i].guid === this.selectArray[s].funcGuid) {
                        this.selectArray.splice(s, 1);
                        s--;
                    }
                }
            }
            /* 在删除 this.checkOptionsOne  里原本选中的，拷贝删除*/
            for (let i = 0 ; i < copyAppry.length; i ++) {
                if($event) { // 如果是全选
                    if(copyAppry[i].ifcheck) { // 把原本选中的去掉，只保留新全选的
                        copyAppry.splice(i, 1);
                        i--;
                    }
                } else { // 如果是全不选
                    if(!copyAppry[i].ifcheck) { // 把原本不选的去掉，保留新全不选的
                        copyAppry.splice(i, 1);
                        i--;

                    }
                }
            }

            for (let d = 0; d < copyAppry.length; d ++) {
                let obj = {
                    exit: 'false',
                    appGuid: copyAppry[d].guidApp,
                    funcGuid: copyAppry[d].guid,
                    fromRole: copyAppry[d].fromRole
                }
                this.selectArray.push(obj);
            }
        } else {
            /* 双层循环，删除this.selectArray 重复的*/
            for(let i = 0 ; i < copyAppry.length; i ++) {
                for(let s = 0; s < this.selectArray.length; s ++ ) {
                    if(copyAppry[i].guid === this.selectArray[s].funcGuid) {
                        this.selectArray.splice(s, 1);
                        s--;
                    }
                }
            }
            /* 在删除 this.checkOptionsOne  里原本选中的，拷贝删除*/
            for (let i = 0 ; i < copyAppry.length; i ++) {
                if($event) { // 如果是全选
                    if(copyAppry[i].ifcheck) { // 把原本选中的去掉，只保留新全选的
                        copyAppry.splice(i, 1);
                        i--;
                    }
                } else { // 如果是全不选
                    if(!copyAppry[i].ifcheck) { // 把原本不选的去掉，保留新全不选的
                        copyAppry.splice(i, 1);
                        i--;

                    }
                }
            }

            for (let d = 0; d < copyAppry.length; d ++) {
                let obj = {
                    exit: 'true',
                    appGuid: copyAppry[d].guidApp,
                    funcGuid: copyAppry[d].guid,
                    fromRole: copyAppry[d].fromRole
                }
                this.selectArray.push(obj);
            }
        }




        this.roleTxt = [];
        if ($event) {
            for (let i = 0; i < this.checkOptionsOne.length; i ++) {
                this.checkOptionsOne[i].checked = true;
                this.checkOptionsOne[i].exit = false; // 勾选了
            }
        } else {
            for(let i = 0; i < this.checkOptionsOne.length; i ++) {
                this.checkOptionsOne[i].checked = false;
                this.checkOptionsOne[i].exit = true; // 没有勾选了
            }
        }
    }

    selectArray  = []; // 默认是空
    selectAll(items, array) {
        this.roleTxt = [];
        if (array.every(item => item.checked ===  true)) { // 利用every属性，判断是否全部选中，如果全部选中，全选按钮为true
            this.checked = true;
        } else {
            this.checked = false;
        }
        array.forEach(item => {
            item.exit = !item.checked + '';
        })
        this.reset(this.checkOptionsOne);
        let obj = {
                exit: items.exit,
                appGuid: items.guidApp,
                funcGuid: items.guid,
                fromRole: items.fromRole
        }

        // console.log(this.selectArray.findIndex(item => JSON.stringify(obj) === JSON.stringify(item)))
        let index = _.findIndex(this.selectArray, function(o) { return o.funcGuid === obj.funcGuid; })
        index  ===  -1 ? this.selectArray.push(obj) : this.selectArray.splice(index, 1);
    }

    cancel() {
        this.isSaveEdit = true; // 保存按钮显示,修改按钮隐藏
        this.isDisabledButton = true; // 改成可以修改
        this.selectArray = []; // 清空
    }


    /*测试*/
    modalVisible = false;
}
